package com.yun2.bms.controller.lend;

import com.yun2.bms.model.Book;
import com.yun2.bms.model.User;
import com.yun2.bms.service.IBookService;
import com.yun2.bms.service.ILendService;
import com.yun2.bms.service.IUserService;
import com.yun2.bms.service.impl.BookServiceImpl;
import com.yun2.bms.service.impl.LendServiceImpl;
import com.yun2.bms.service.impl.UserServiceImpl;
import com.yun2.bms.utils.StringUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/6/15
 */

public class LendController implements Initializable {

    private ILendService lendService = new LendServiceImpl();

    private IUserService userService = new UserServiceImpl();

    private IBookService bookService = new BookServiceImpl();

    private ObservableList<Book> bookData = FXCollections.observableArrayList();

    @FXML
    private Label lblUserInfo;

    @FXML
    private TableColumn<Book, Book> remainNumber;

    @FXML
    private TableColumn<Book, Book> author;

    @FXML
    private TableView<Book> bookTable;

    @FXML
    private Button btnQuery;

    @FXML
    private TableColumn<Book, Book> bookName;

    @FXML
    private TableColumn<Book, Book> categoryName;

    @FXML
    private TableColumn<Book, Book> lendingQuantity;

    @FXML
    private Pagination pager;

    @FXML
    private Button btnAdd;

    @FXML
    private TableColumn<Book, Book> bookNumber;

    @FXML
    private TableColumn<Book, Book> price;

    @FXML
    private TextField tfUserInfo;

    @FXML
    private TableColumn<Book, Book> publisher;

    @FXML
    private TableColumn<Book, Book> id;

    @FXML
    private Button btnReset;

    @FXML
    void add(ActionEvent event) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        String info = "";

        int userId = Integer.valueOf(this.tfUserInfo.getText().trim());
        User user = this.userService.get(userId);
        //1 获取用户要借阅的图书
        Book book = this.bookTable.getSelectionModel().getSelectedItem();
        if (book != null && user != null) {
            // 确认信息
            String msg = "是否要将图书" + book.getBookName() + "借出给用户" + user.getUserName() + "[账号：" + user.getId() + "]吗？";
            Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, msg);
            confirmation.setHeaderText("提示信息");
            confirmation.showAndWait();
            // 用户点击确定之后开始借阅图书
            if (confirmation.getResult().getButtonData().isDefaultButton()) {
                int bookId = book.getId();
                //在图书借出之前，还应该有的检查:（业务逻辑）
                //1 读者已经借阅了指定的图书，同一本书一个用户指定借阅一次（这个人是否已经借阅了这本书）
                boolean flag1 = this.lendService.bookIsLendedByUserId(bookId,userId);
                int count = this.lendService.getLendedNumberByUserId(userId);
                if(flag1){
                    info = "该读者已经借阅过该图书且尚未归还，请先还书！";
                }else if(count > user.getMaxLendNumber()){
                    //2 读者如果已经达到最大的借阅数量，也不能继续借书
                    info = "该读者达到最大借阅数量，请先还书！";
                }else if(book.getRemainNumber() == 0){
                    //3 如果图书剩余数量为0，也不能继续借书
                    info = "图书剩余数量为0，借书失败！";
                }else{
                    //将图书借出
                    int ret = this.lendService.add(userId, bookId);
                    //更新表格中的图书数据
                    if (ret > 0) {
                        book.setLendingQuantity(book.getLendingQuantity() + 1);
                        book.setRemainNumber(book.getBookNumber() - book.getLendingQuantity());
                        //更新用户的借阅信息
                        user = this.userService.getUser4Lend(userId);
                        updateUserInfo(user);
                        info = "图书借阅成功！";
                    } else {
                        info = "图书借阅失败！";
                    }
                }
            }else{
                return;
            }
        } else {
            info = "请指定读者或者图书信息！";
        }
        alert.setTitle("提示信息");
        alert.setHeaderText(info);
        alert.showAndWait();
    }

    @FXML
    void query(ActionEvent event) {

        //1 获取用户的信息
        String id = this.tfUserInfo.getText();
        if (StringUtils.isNotBlank(id)) {
            //2 查询用户的信息
            User currentUser = this.userService.getUser4Lend(Integer.valueOf(id));
            updateUserInfo(currentUser);
            //3 显示所有图书信息
            List<Book> bookList = this.bookService.getAll();
            bookData.clear();
            bookData.addAll(bookList);
            this.bookTable.setItems(bookData);
        }
    }

    private void updateUserInfo(User currentUser){
        StringBuilder info = new StringBuilder();
        info.append("用户编号：").append(currentUser.getId()).append(",");
        info.append("用户姓名：").append(currentUser.getUserName()).append(",");
        info.append("用户角色：").append(currentUser.getRoleCn()).append(",");
        info.append("最大借阅数量：").append(currentUser.getMaxLendNumber()).append(",");
        //下面的信息必须去lend表中去获取
        info.append("已经借阅数量：").append(currentUser.getMyLendedNumber()).append("。");
        this.lblUserInfo.setText(info.toString());
    }

    @FXML
    void reset(ActionEvent event) {

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
}
